package com.kevms.phonewars;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;

/** 
* @class Profile
* 
* @brief Activity used to provide user customization.
* 
* This Activity provides the user with several customization
* options such as the background color of the application, 
* their user name, and their profile picture.
*/ 
public class Profile extends Activity {
	
	private Context mContext;
	private WebService mWebService = null;
	private EditText etName;
	
	private SQLiteDatabase db;
	private MySQLiteHelper dbHelper;
	private Bitmap myBitmap = null;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.profile);
		mContext = this;
		
		dbHelper = MySQLiteHelper.getInstance(getApplicationContext());
		db = dbHelper.getWritableDatabase();
		LinearLayout l = (LinearLayout)findViewById(R.id.topLayout);
    	l.setBackgroundColor(dbHelper.getBgColor(db));
		
    	loadProfilePic();
    	
		etName = (EditText)findViewById(R.id.etName);
		mWebService = WebService.getInstance(mContext);
		
		try {
			JSONObject jObject = mWebService.getName();
			etName.setText(jObject.getString("name"));
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		Button btnApply = (Button)findViewById(R.id.btnApply);
		
		btnApply.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				try {
					mWebService.setName(etName.getText().toString());
					finish();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		
		Spinner spinner = (Spinner) findViewById(R.id.spinnerBgColor);
	    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
	            this, R.array.bgcolor_array, android.R.layout.simple_spinner_item);
	    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    spinner.setAdapter(adapter);
	    
	    spinner.setSelection(getIndex(dbHelper.getBgColor(db)));
	    spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
	    
	    Button btnPic = (Button)findViewById(R.id.btnPic);
		
		btnPic.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setType("image/*");
				intent.setAction(Intent.ACTION_GET_CONTENT);
				startActivityForResult(Intent.createChooser(intent, "Select Picture"),1);
			}
		});
	}
	
	public class MyOnItemSelectedListener implements OnItemSelectedListener {

		public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
			dbHelper.setBgColor(db, COLORS[pos]);
			
			LinearLayout l = (LinearLayout)findViewById(R.id.topLayout);
	    	l.setBackgroundColor(COLORS[pos]);
		}

		public void onNothingSelected(AdapterView<?> arg0) {
			
		}
	}
	
	private int getIndex(int color) {
		for(int i = 0; i < COLORS.length; i++) {
			if(COLORS[i] == color)
				return i;
		}
		return 0;
	}
	
	// To handle when an image is selected from the browser, add the following to your Activity
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) { 
		if (resultCode == RESULT_OK) {
			if (requestCode == 1) {
				// currImageURI is the global variable I'm using to hold the content:// URI of the image
				Uri currImageURI = data.getData();
				dbHelper.setPicPath(db, getRealPathFromURI(currImageURI));
				
				loadProfilePic();
			}
		}
	}

	// And to convert the image URI to the direct file system path of the image file
	public String getRealPathFromURI(Uri contentUri) {
	
		// can post image
		String [] proj={MediaStore.Images.Media.DATA};
		Cursor cursor = managedQuery( contentUri,
				proj,  // Which columns to return
				null,  // WHERE clause; which rows to return (all rows)
				null,  // WHERE clause selection arguments (none)
				null); // Order-by clause (ascending by name)
		int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		
		return cursor.getString(column_index);
	}
	
	public void loadProfilePic() {
		String path = dbHelper.getPicPath(db);
		if(path == null)
			return;
		File imgFile = new  File(path);
		if(imgFile.exists()) {
			if(myBitmap != null) {
				myBitmap.recycle();
				System.gc();
			}
		    //myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
			myBitmap = decodeFile(imgFile);
		    ImageView ivPic = (ImageView) findViewById(R.id.ivPic);
		    ivPic.setImageBitmap(myBitmap);
		}
	}
	
	//decodes image and scales it to reduce memory consumption
		private Bitmap decodeFile(File f){
		    try {
		        //Decode image size
		        BitmapFactory.Options o = new BitmapFactory.Options();
		        o.inJustDecodeBounds = true;
		        BitmapFactory.decodeStream(new FileInputStream(f),null,o);

		        //The new size we want to scale to
		        final int REQUIRED_SIZE=140;

		        //Find the correct scale value. It should be the power of 2.
		        int scale=1;
		        while(o.outWidth/scale/2>=REQUIRED_SIZE && o.outHeight/scale/2>=REQUIRED_SIZE)
		            scale*=2;

		        //Decode with inSampleSize
		        BitmapFactory.Options o2 = new BitmapFactory.Options();
		        o2.inSampleSize=scale;
		        return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
		    } catch (FileNotFoundException e) {}
		    return null;
		}
	
	static final Integer[] COLORS = new Integer[] {
    	Color.BLACK, Color.BLUE, Color.RED, Color.GREEN, Color.CYAN, Color.MAGENTA, Color.WHITE
    };
}
